package com.enation.app.javashop.consumer.job.execute.impl;

import com.enation.app.javashop.consumer.job.execute.EveryHourExecute;
import com.enation.app.javashop.core.payment.plugin.weixin.signaturer.WechatSignaturer;
import com.enation.app.javashop.core.payment.plugin.weixin.signaturer.WechatTypeEnmu;
import com.enation.app.javashop.core.system.enums.WeChatPublicConstant;
import com.enation.app.javashop.core.system.enums.WeixinMiniproConstants;
import com.enation.app.javashop.core.system.service.WechatPublicManager;
import com.enation.app.javashop.framework.util.EnvironmentUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 小程序和微信公众号都刷新
 * 生产环境小程序accessToken定时刷新任务
 */
@Service
public class AccessTokenUpdateJob implements EveryHourExecute{

    protected final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    private WechatSignaturer wechatSignaturer;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private WechatPublicManager wechatPublicManager;

    /**
     * 每小时执行
     */
    @Override
    public void everyHour() {
        if(EnvironmentUtils.isProd()){
            // 生产环境刷新小程序token
            try {
                String accessToken = wechatSignaturer.getCgiAccessToken(WechatTypeEnmu.MINI);

                if(StringUtils.isNotBlank(accessToken)){
                    stringRedisTemplate.opsForValue().set(WeixinMiniproConstants.MINIPRO_ACCESS_TOKEN, accessToken);
                }else{
                    logger.info("微信小程序accessToken刷新失败，未获取到正确值");
                }
            } catch (Exception e) {
                logger.error("微信小程序accessToken刷新失败", e);
                e.printStackTrace();
            }

            // 生产环境刷新公众号token
            try {
                String token = wechatPublicManager.getTokenFromWeiXin();
                if(StringUtils.isNotBlank(token)){
                    stringRedisTemplate.opsForValue().set(WeChatPublicConstant.WEIXIN_PUBLIC_TOKEN, token);
                }else{
                    logger.info("微信公众号accessToken刷新失败，未获取到正确值");
                }
            } catch (Exception e) {
                logger.info("微信公众号accessToken刷新失败", e);
                e.printStackTrace();
            }
        }
    }
}
